import { Component, OnInit } from '@angular/core';
import { NzMessageService, NzModalService } from 'ng-zorro-antd';
import { _HttpClient, ModalHelper } from '@delon/theme';
import { BusinessTaskEditComponent } from './edit/edit.component';
@Component({
  selector: 'business-task',
  templateUrl: './task.component.html',
})
export class BusinessTaskComponent implements OnInit {
  queryStr: any = {
    offset: 0,
    limit: 10
  };
  loading = false;
  data: any[] = [];
  constructor(
    private http: _HttpClient,
    private modal: ModalHelper,
    private modalSrv: NzModalService,
    public msg: NzMessageService) {}
  ngOnInit() {
    this.getData();
  }
  getData() {
    this.loading = true;
    this.http.get('api/task/list', this.queryStr).subscribe((res: any) => {
      this.data = res.objects;
      this.loading = false;
    });
  }
  remove(id) {
    this.modalSrv.confirm({
      nzTitle     : '是否确认删除?',
      nzContent   : '<b style="color: red;">删除后不可恢复</b>',
      nzOkText    : '是',
      nzOkType    : 'danger',
      nzOnOk      : () => {
        this.http.delete('api/task/delete/', {id}).subscribe((res: any) => {
          if(res.success) {
            this.msg.success(`删除成功`);
            this.getData();
          }else{
            this.msg.error(`删除失败`);
          }
        }, () => {
          this.msg.error(`网络或服务器错误`);
        });
      },
      nzCancelText: '否',
      nzOnCancel  : () => console.log('Cancel')
    });
  }
  reset(ls: any[]) {
    for (const item of ls) item.value = false;
    this.getData();
  }
  // 编辑新增
  openEdit(i: any = {}) {
    this.modal.create(BusinessTaskEditComponent, { i }, { size: 'md' })
      .subscribe(res => {
        if(i._id) {
          res['_id'] = i._id;
          this.http.patch('api/task/update/', res).subscribe((res: any) => {
            if(res.success) {
              this.msg.success(`修改成功`);
              this.getData();
            }else{
              this.msg.error(`任务已存在`);
            }
          }, () => {
            this.msg.error(`网络或服务器错误`);
          });
        }else {
          this.http.post('api/task/add/', res).subscribe((res: any) => {
            if(res.success) {
              this.msg.success(`添加成功`);
              this.getData();
            }else{
              this.msg.error(`任务已存在`);
            }
          }, () => {
            this.msg.error(`网络或服务器错误`);
          });
        }
      });
  }
}
